package com.yuyou.fn.tms.service.impl;

import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.github.wens.mybatisplus.toolkit.IdWorker;
import com.google.common.collect.Lists;
import com.yuyou.fn.common.constant.ClassLevelEnum;
import com.yuyou.fn.common.constant.SexEnum;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.Principals;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.crm.constant.PriorityEnum;
import com.yuyou.fn.crm.entity.CrmDepartment;
import com.yuyou.fn.crm.entity.CustomerResource;
import com.yuyou.fn.crm.entity.FromCategory;
import com.yuyou.fn.crm.service.ICrmDepartmentService;
import com.yuyou.fn.crm.service.ICustomerResourceService;
import com.yuyou.fn.crm.service.IFromCategoryService;
import com.yuyou.fn.crm.service.IMarketImportService;
import com.yuyou.fn.crm.vo.ImportCustomerResourceVo;
import com.yuyou.fn.educational.entity.*;
import com.yuyou.fn.educational.service.*;
import com.yuyou.fn.educational.vo.ImportCourseClassVo;
import com.yuyou.fn.tms.service.IResourceSyncService;
import com.yuyou.fn.tms.vo.PageQueryResult;

import com.yuyou.fn.tms.vo.resource.*;
import com.yuyou.fn.platform.entity.City;
import com.yuyou.fn.platform.entity.CustomerUser;
import com.yuyou.fn.platform.entity.District;
import com.yuyou.fn.platform.entity.Province;
import com.yuyou.fn.platform.service.ICityService;
import com.yuyou.fn.platform.service.IDistrictService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.sql.Time;
import java.util.*;

@Service
public class ResourceSyncServiceImpl implements IResourceSyncService {

    /*某些项只给这些区域数据*/
    private List<Long> areaTeamIds= Arrays.asList(564701030634225664L);

    /*区域和城市的关系*/
    private Map<Long,Long> areaTeamCityRelativeMap=new HashMap<>();


    @PostConstruct
    private void init(){
        /*广州区域对应广州市*/
        areaTeamCityRelativeMap.put(564701030634225664l,1l);
    }

    @Resource
    private ICampusService campusService;

    @Resource
    private ICityService cityService;

    @Resource
    private IDistrictService districtService;

    @Resource
    private IBaseGradeService baseGradeService;

    @Resource
    private IBaseSubjectService baseSubjectService;

    @Resource
    private IStudentService studentService;

    @Resource
    private ICustomerResourceService customerResourceService;

    @Resource
    private IStudentRegService studentRegService;

    @Resource
    private ICourseClassService courseClassService;

    @Resource
    private ICrmDepartmentService crmDepartmentService;

    @Resource
    private IMarketImportService marketImportService;

    @Resource
    private IFromCategoryService fromCategoryService;
    @Override
    public List<ResourceDistrict> syncAreaForZyRes(Date updateTime) {
        Example<District> example = District.createExample();
        example.orderBy("updateTime");
        Example.Criteria criteria = example.createCriteria();
        fillCondition(criteria,updateTime,null );
        List<District> districtList = districtService.findListByExample(example);
        List<ResourceDistrict> list = Lists.transform(districtList, item -> {
            return new ResourceDistrict(item);
        });
        return list;
    }

    @Override
    public List<ResourceCampus> syncDepartmentForZyRes(Date updateTime) {
        Example<Campus> example = Campus.createExample();
        example.orderBy("updateTime");
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("state",1);
        fillCondition(criteria,updateTime,null );
        fillAreaTeamsCondition(criteria);
        List<Campus> campusList = campusService.findListByExample(example);
        Map<String,City> cityMap=cityService.findAllCityMapByProvinceNameCityName();
        Map<String,District> districtMap=districtService.findAllMapByProvinceCityDistrictName();
        List<ResourceCampus> list = Lists.transform(campusList, item -> {
            City city=null;
            District district=null;
            if (StringUtils.isNotEmpty(item.getProvince()) && StringUtils.isNotEmpty(item.getCity()) && StringUtils.isNotEmpty(item.getDistrict())){
                String provinceKey=item.getProvince().replaceAll("省","");
                String cityKey=provinceKey+"_"+item.getCity().replaceAll("市","");
                String districtKey=cityKey+"_"+item.getDistrict();
                city=cityMap.get(cityKey);
                district=districtMap.get(districtKey);
            }

            return new ResourceCampus(item,city,district);
        });
        return list;


    }

    @Override
    public List<ResourceCity> syncCityForZyRes(Date updateTime) {
        Example<City> example = City.createExample();
        example.orderBy("updateTime");
        Example.Criteria criteria = example.createCriteria();
        fillCondition(criteria,updateTime,null );
        List<City> cityList = cityService.findListByExample(example);
        List<ResourceCity> list = Lists.transform(cityList, item -> {
            return new ResourceCity(item);
        });

        return list;
    }

    @Override
    public List<ResourceGrade> syncGradeForZyRes(Date updateTime) {
        List<BaseGrade> baseGradeList = baseGradeService.findAllOrderGrade();
        List<ResourceGrade> list = Lists.transform(baseGradeList, item -> {
            return new ResourceGrade(item);
        });
        return list;
    }

    @Override
    public List<ResourceSubject> syncSubtForZyRes(Date updateTime) {
        List<BaseSubject> baseSubjectList = baseSubjectService.findAllFromCache();
        List<ResourceSubject> list = Lists.transform(baseSubjectList, item -> {
            return new ResourceSubject(item);
        });
        return list;
    }

    @Override
    public PageQueryResult<ResourceStudent> syncStudentForZyRes(PageRequestParam pageRequestParam) {
        Example<Student> example = Student.createExample();
        example.orderBy("updateTime");
        Example.Criteria criteria = example.createCriteria();
        fillCondition(criteria,pageRequestParam.getLastModifyTime(),null );

        Page<Student> page = studentService.findPageByExample(example,pageRequestParam.getPageIndex(),pageRequestParam.getPageSize());
        List<ResourceStudent> list = Lists.transform(page.getRecords(), item -> {
            return new ResourceStudent(item);
        });
        return new PageQueryResult<>(page.getTotal(),list);
    }

    @Override
    public PageQueryResult<ResourceReg> syncRegistForZyRes(PageRequestParam pageRequestParam) {
        Example<StudentReg> example=StudentReg.createExample();
        example.orderBy("updateTime");
        Example.Criteria criteria = example.createCriteria();
        fillCondition(criteria,pageRequestParam.getLastModifyTime() ,null);
        fillAreaTeamsCondition(criteria);
        Page<StudentReg> page = studentRegService.findPageByExample(example, pageRequestParam.getPageIndex(), pageRequestParam.getPageSize());
        List<Long> classIds = Utils.unique(BeanUtils.toList(page.getRecords(), "classId"));
        List<CourseClass> courseClassList=courseClassService.findByIds(classIds,CourseClass.BASE_FIELDS);
        Map<Long, CourseClass> classMap = BeanUtils.toMap(courseClassList, "classId");
        List<ResourceReg> list = Lists.transform(page.getRecords(), item -> {
            CourseClass courseClass=classMap.get(item.getClassId());
            return new ResourceReg(item,courseClass);
        });
        return new PageQueryResult<>(page.getTotal(),list);
    }

    @Override
    public PageQueryResult<ResourceCustomer> syncImportLogForZyRes(PageRequestParam pageRequestParam) {
        Example<CustomerResource> example=CustomerResource.createExample();
        example.orderBy("updateTime");
        Example.Criteria criteria = example.createCriteria();
        fillCondition(criteria,pageRequestParam.getLastModifyTime() ,null);
        fillAreaTeamsCondition(criteria);
        Page<CustomerResource> page = customerResourceService.findPageByExample(example, pageRequestParam.getPageIndex(), pageRequestParam.getPageSize());
        List<ResourceCustomer> list = Lists.transform(page.getRecords(), item -> {
            return new ResourceCustomer(item);
        });
        return new PageQueryResult<>(page.getTotal(),list);
    }

    @Override
    public List<ResourceLevel> syncClvForZyRes(Date updateTime) {
        List<ResourceLevel> list=new ArrayList<>();
        for (ClassLevelEnum classLevelEnum:ClassLevelEnum.values()){
            if (classLevelEnum.ordinal()==0){
                continue;
            }
            ResourceLevel resourceLevel=new ResourceLevel();
            resourceLevel.setClvId((long)classLevelEnum.ordinal());//层级id
            resourceLevel.setClvName(classLevelEnum.name());//层次名称
            resourceLevel.setClvOrder(classLevelEnum.ordinal()+"");//层级值(课程分层精英>培优>提高)
            resourceLevel.setModifyTime(TimeUtils.now());//最后修改时间
            resourceLevel.setCreateTime(TimeUtils.now());
            resourceLevel.setState(0);//是否删除(0否,1是)
            list.add(resourceLevel);
        }
        return list;
    }

    @Override
    @Transactional
    public void receiveResFromRmp(long areaTeamId,String departmentName,List<ResourceReceive> resourceReceiveList) {
        if (resourceReceiveList.isEmpty()){
            return;
        }
        CrmDepartment crmDepartment=crmDepartmentService.findByAreaTeamIdAndName(areaTeamId,departmentName);

        List<FromCategory> fromCategoryList=fromCategoryService.findAllFromCategoryByAreaTeamId(areaTeamId);
        Map<Long,FromCategory> fromCategoryMap=BeanUtils.toMap(fromCategoryList,"categoryId");

        Map<String,FromCategory> bigCategoryMap=new HashMap<>(); //key=categoryName;
        Map<String,FromCategory> smallCategoryMap=new HashMap<>();//key=parentCategoryName_categoryName;

        for (FromCategory fromCategory:fromCategoryList){
            if (fromCategory.getParentCategoryId().equals(0l)){
                bigCategoryMap.put(fromCategory.getCategoryName(),fromCategory);
            }else {
                FromCategory parent=fromCategoryMap.get(fromCategory.getParentCategoryId());
                String key=parent.getCategoryName()+"_"+fromCategory.getCategoryName();
                smallCategoryMap.put(key,fromCategory);
            }
        }



        if (crmDepartment==null){
            crmDepartment=new CrmDepartment();
            crmDepartment.setDepartmentId(IdWorker.getId());
            crmDepartment.setDepartmentName(departmentName);
            crmDepartment.setUpdateTime(TimeUtils.now());
            crmDepartment.setCreateTime(TimeUtils.now());
            crmDepartment.setAreaTeamId(areaTeamId);
            crmDepartment.setOperatorId(0l);
            crmDepartment.setOperatorName("系统");
            crmDepartmentService.insertSelective(crmDepartment);
        }

        List<ImportCustomerResourceVo> importCustomerResourceVos=new ArrayList<>(resourceReceiveList.size());

        List<FromCategory> saveList=new ArrayList<>();

        for (ResourceReceive resourceReceive:resourceReceiveList){
            ImportCustomerResourceVo importCustomerResourceVo=new ImportCustomerResourceVo();
            importCustomerResourceVo.setStudentName(resourceReceive.getResName());
            importCustomerResourceVo.setPhoneNo(resourceReceive.getResPhone());
            importCustomerResourceVo.setProjectName(resourceReceive.getResActivityName());
            importCustomerResourceVo.setProjectTime(Utils.formatDate(resourceReceive.getResActivityTime(),"yyyy-MM-dd HH:mm:ss"));
            importCustomerResourceVo.setFromBigCategoryName(resourceReceive.getTisNames());
            importCustomerResourceVo.setFromSmallCategoryName(resourceReceive.getTistNames());
            importCustomerResourceVo.setPriority(resourceReceive.getResLevel());
            importCustomerResourceVo.setSex(resourceReceive.getResSex());
            importCustomerResourceVo.setCampusName(resourceReceive.getResDeptName());
            importCustomerResourceVo.setGradeName(resourceReceive.getResGrade());
            importCustomerResourceVos.add(importCustomerResourceVo);

            FromCategory bigCategory=bigCategoryMap.get(resourceReceive.getTisNames());
            if (bigCategory==null){
                bigCategory=new FromCategory();
                bigCategory.setAreaTeamId(areaTeamId);
                bigCategory.setCategoryId(IdWorker.getId());
                bigCategory.setCategoryName(resourceReceive.getTisNames());
                bigCategory.setParentCategoryId(0L);
                bigCategory.setCreateTime(TimeUtils.now());
                bigCategory.setUpdateTime(TimeUtils.now());
                bigCategoryMap.put(bigCategory.getCategoryName(),bigCategory);
                saveList.add(bigCategory);
            }
            String smallKey=resourceReceive.getTisNames()+"_"+resourceReceive.getTistNames();
            FromCategory smallCategory=smallCategoryMap.get(smallKey);
            if (smallCategory==null){
                smallCategory=new FromCategory();
                smallCategory.setAreaTeamId(areaTeamId);
                smallCategory.setParentCategoryId(bigCategory.getCategoryId());
                smallCategory.setCategoryName(resourceReceive.getTistNames());
                smallCategory.setUpdateTime(TimeUtils.now());
                smallCategory.setCreateTime(TimeUtils.now());
                smallCategory.setCategoryId(IdWorker.getId());
                smallCategoryMap.put(smallKey,smallCategory);
                saveList.add(smallCategory);
            }


        }
        if (saveList.size()>0){
            fromCategoryService.insertBatch(saveList);
        }
        Principals.Principal principal = new Principals.Principal(0L, "集团资源导入");
        marketImportService.importCustomerResource(areaTeamId,crmDepartment.getDepartmentId(),importCustomerResourceVos, principal);

    }


    private void fillCondition(Example.Criteria criteria,Date updateTime,String queryTime) {
        if (StringUtils.isEmpty(queryTime)){
            queryTime="updateTime";
        }
        criteria.andGreaterThanOrEqualTo(queryTime,updateTime);

    }

    private void fillAreaTeamsCondition(Example.Criteria criteria) {
        criteria.andIn("areaTeamId", areaTeamIds);

    }
}
